/**
 * Created by DouYaHu on 2018/5/10.
 */


/**
 * table初始化方法
 */
function initdataTable(tableName, lengthMenu, url, columns,strategyId) {
    var dataTable = $("#" + tableName).dataTable(
        {
            sPaginationType: "full_numbers", //分页风格，full_number会把所有页码显示出来（大概是，自己尝试）
            searching: false,//搜索
            ordering: false,//是否启用排序
            bAutoWidth: true,
            bProcessing: true, //是否显示加载
            sAjaxSource: url, //请求资源路径
            serverSide: true, //开启服务器处理模式
            /*
             使用ajax，在服务端处理数据
             sSource:即是"sAjaxSource"
             aoData:要传递到服务端的参数
             fnCallback:处理返回数据的回调函数
             */
            fnServerData: function (sSource, aoData, fnCallback) {
                $.ajax({
                    'type': 'POST',
                    "url": sSource,
                    "dataType": "json",
                    "data": {"aodata": JSON.stringify(aoData), strategyId},
                    "success": function (resp) {
                        fnCallback(resp);
                    }
                });
            },
            oLanguage: {//语言设置
                "sLengthMenu": lengthMenu,
                "sProcessing": "处理中...",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(获取 _MAX_ 项结果)",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
            },
            bProcessing: true, //开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            bServerSide: true, //开启服务器模式，使用服务器端处理配置datatable。
            // 注意：sAjaxSource参数也必须被给予为了给datatable源代码来获取所需的数据对于每个画。
            // 这个翻译有点别扭。开启此模式后，你对datatables的每个操作 每页显示多少条记录、下一页、上一页、排序（表头）、搜索，这些都会传给服务器相应的值。
            columns: columns,
            infoCallback: function (settings, start, end, max, total, pre) {
                $("#" + tableName + " input[type='checkbox']").iCheck("uncheck");
                // return "显示第"+start+"至"+end+"项结果，共"+total+"项";
                return pre;
            }
        }
    );
    return dataTable;
}


/**
 * jquery 初始化form插件，传入一个json对象，为form赋值
 * version: 1.0.0-2013.06.24
 * @requires jQuery v1.5 or later
 * Copyright (c) 2013
 * note:  1、此方法能赋值一般所有表单，但考虑到checkbox的赋值难度，以及表单中很少用checkbox，这里不对checkbox赋值
 *          2、此插件现在只接收json赋值，不考虑到其他的来源数据
 *          3、对于特殊的textarea，比如CKEditor,kindeditor...，他们的赋值有提供不同的自带方法，这里不做统一，如果项目中有用到，不能正确赋值，请单独赋值
 */
(function ($) {
    $.fn.extend({
        initForm: function (options) {
            //默认参数
            var defaults = {
                jsonValue: "",
                isDebug: false	//是否需要调试，这个用于开发阶段，发布阶段请将设置为false，默认为false,true将会把name value打印出来
            }
            //设置参数
            var setting = $.extend({}, defaults, options);
            var form = this;
            var jsonValue = setting.jsonValue;
            //如果传入的json字符串，将转为json对象
            if ($.type(setting.jsonValue) === "string") {
                jsonValue = $.parseJSON(jsonValue);
            }
            //如果传入的json对象为空，则不做任何操作
            if (!$.isEmptyObject(jsonValue)) {
                var debugInfo = "";
                $.each(jsonValue, function (key, value) {
                    //是否开启调试，开启将会把name value打印出来
                    if (setting.isDebug) {
                        alert("name:" + key + "; value:" + value);
                        debugInfo += "name:" + key + "; value:" + value + " || ";
                    }
                    var formField = form.find("[name='" + key + "']");
                    if ($.type(formField[0]) === "undefined") {
                        if (setting.isDebug) {
                            alert("can not find name:[" + key + "] in form!!!");	//没找到指定name的表单
                        }
                    } else {
                        var fieldTagName = formField[0].tagName.toLowerCase();
                        if (fieldTagName == "input") {
                            if (formField.attr("type") == "radio") {
                                $("input:radio[name='" + key + "'][value='" + value + "']").attr("checked", "checked");
                            } else {
                                formField.val(value);
                            }
                        } else if (fieldTagName == "select") {
                            // $("#statusxxx").find("option[text='" + value + "']").attr("selected", false);
                            $("#statusxxx").find("option:contains('" + value + "')").attr("selected", true);
                            //do something special
                            // formField.find("option").attr("selected",false);
                            // formField.find("option:contains('"+value+"')").attr("selected",true).trigger("change");
                            // formField.find("option[text='"+value+"']").attr('selected', true);
                            // formField.val(value);
                        } else if (fieldTagName == "textarea") {
                            //do something special
                            formField.val(value);
                        } else {
                            formField.val(value);
                        }
                    }
                })
                // if(setting.isDebug){
                // 	alert(debugInfo);
                // }
            }
            return form;	//返回对象，提供链式操作
        }
    });
})(jQuery)


/***
 * 初始化Alert方法
 * @param code
 * @param message
 */
function initAlert(message) {
    BootstrapDialog.show({
        title: '系统提示',
        message: message,
        cssClass: 'login-dialog',
        buttons: [{
            label: '确定',
            action: function (dialogRef) {
                dialogRef.close();
            }
        }],
        onshown: function (dialogRef) {
            setTimeout(function () {
                dialogRef.close();
            }, 2000);
        },
    });
}


//验证初始化
function initValidator(form, fields, submit, url) {
    form.bootstrapValidator({
        live: 'submitted',//验证时机，enabled是内容有变化就验证（默认），disabled和submitted是提交再验证
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        message: '这个值没有被验证',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: fields,
        submitButtons: submit,
    });

    $(submit).click(function () {
        // var token = $.cookie('csrftoken');
        var bv = form.data('bootstrapValidator').validate();
        if (bv.isValid()) {
            console.log(form.serialize());
            $.post(url, form.serialize(), function (res) {
                initAlert(res.code, res.message);
            });
        }
    });
}
function cget(symbol, gid){
    $('#loading-center-absolute').css('display', 'block');
    $.get("/strategy/backtest/detail/candlestik", {'backtestId': gid, 'symbol': symbol}, function (result) {
        var myChart = echarts.init(document.getElementById('candlestik'));
        myChart.clear();
        if (result != null) {
            if (result.is_KLine) {
                var upColor = '#ec0000';
                var upBorderColor = '#8A0000';
                var downColor = '#00da3c';
                var downBorderColor = '#008F28';

                // 数据意义：开盘(open)，收盘(close)，最低(lowest)，最高(highest)
                var data0 = splitData(result.data);

                function splitData(rawData) {
                    var categoryData = [];
                    var values = [];
                    for (var i = 0; i < rawData.length; i++) {
                        categoryData.push(rawData[i].splice(0, 1)[0]);
                        values.push(rawData[i])
                    }
                    return {
                        categoryData: categoryData,
                        values: values
                    };
                }

                function calculateMA(dayCount) {
                    var result = [];
                    for (var i = 0, len = data0.values.length; i < len; i++) {
                        if (i < dayCount) {
                            result.push('-');
                            continue;
                        }
                        var sum = 0;
                        for (var j = 0; j < dayCount; j++) {
                            sum += data0.values[i - j][1];
                        }
                        result.push((sum / dayCount).toFixed(2));
                    }
                    return result;
                }


                var option = option = {

                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross'
                        }
                    },
                    grid: {
                        left: '5%',   // 与容器左侧的距离
                        right: '5%', // 与容器右侧的距离
                        top: '15%',   // 与容器顶部的距离
                        bottom: '22%', // 与容器底部的距离
                    },
                    legend: {
                        data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30']
                    },
                    xAxis: {
                        type: 'category',
                        data: data0.categoryData,
                        scale: true,
                        boundaryGap: false,
                        axisLine: {onZero: false},
                        splitLine: {show: false},
                        splitNumber: 20,
                        min: 'dataMin',
                        max: 'dataMax'
                    },
                    yAxis: {
                        scale: true,
                        splitArea: {
                            show: true
                        }
                    },
                    dataZoom: [
                        {
                            type: 'inside',
                            start: 50,
                            end: 100
                        },
                        {
                            show: true,
                            type: 'slider',
                            y: '90%',
                            start: 50,
                            end: 100
                        }
                    ],
                    series: [
                        {
                            name: '日K',
                            type: 'candlestick',
                            data: data0.values,
                            itemStyle: {
                                normal: {
                                    color: upColor,
                                    color0: downColor,
                                    borderColor: upBorderColor,
                                    borderColor0: downBorderColor
                                }
                            },
                        },
                        {
                            name: 'MA5',
                            type: 'line',
                            data: calculateMA(5),
                            smooth: true,
                            lineStyle: {
                                normal: {opacity: 0.5}
                            }
                        },
                        {
                            name: 'MA10',
                            type: 'line',
                            data: calculateMA(10),
                            smooth: true,
                            lineStyle: {
                                normal: {opacity: 0.5}
                            }
                        },
                        {
                            name: 'MA20',
                            type: 'line',
                            data: calculateMA(20),
                            smooth: true,
                            lineStyle: {
                                normal: {opacity: 0.5}
                            }
                        },
                        {
                            name: 'MA30',
                            type: 'line',
                            data: calculateMA(30),
                            smooth: true,
                            lineStyle: {
                                normal: {opacity: 0.5}
                            }
                        },
                        {
                            name: '买入',
                            symbolSize: 10,
                            data: result.Buy_TradePrice,
                            type: 'scatter',
                            itemStyle: {
                                normal: {
                                    color: '#FF0000',
                                    lineStyle: {
                                        color: '#FF0000'
                                    }
                                }
                            },
                            tooltip: {
                                trigger: 'item',
                                padding: 5,
                                backgroundColor: '#FF0000',
                                borderColor: '#FF0000',
                                borderWidth: 1,
                                formatter: function (obj) {
                                    var value = obj.value;
                                    return   "时间：" + value[0]+ '<br>'+obj.seriesName + "：" + value[1]
                                }
                            }
                        },
                        {
                            name: '卖出',
                            symbolSize: 10,
                            data: result.Sell_TradePrice,
                            type: 'scatter',
                            itemStyle: {
                                normal: {
                                    color: '#008000',
                                    lineStyle: {
                                        color: '#008000'
                                    }
                                }
                            },
                            tooltip: {
                                trigger: 'item',
                                padding: 5,
                                backgroundColor: '#008000',
                                borderColor: '#008000',
                                borderWidth: 1,
                                formatter: function (obj) {
                                    var value = obj.value;
                                    return  "时间：" + value[0]+ '<br>' +obj.seriesName + "：" + value[1]
                                }
                            },
                        }

                    ]
                };
                myChart.setOption(option);

            } else {
                var option = {
                    legend: {
                        data: ['买入', '卖出']
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function (obj) {

                            return '时间：' + obj[0].axisValue+ '<br>' + obj[0].seriesName + "：" + obj[0].value
                        }
                    },
                    grid: {
                        left: '5%',   // 与容器左侧的距离
                        right: '5%', // 与容器右侧的距离
                        top: '15%',   // 与容器顶部的距离
                        bottom: '22%', // 与容器底部的距离
                    },
                    dataZoom: [
                        {
                            show: true,
                            realtime: true,
                            start: 65,
                            end: 85
                        },
                        {
                            type: 'inside',
                            realtime: true,
                            start: 65,
                            end: 85
                        }
                    ],
                    xAxis: {
                        type: 'category',
                        data: null,
                        scale: true
                    },
                    yAxis: {
                        type: 'value',
                        scale: true
                    },
                    series: [{
                        name: '最新价',
                        data: null,
                        type: 'line',
                    },
                        {
                            name: '买入',
                            symbolSize: 10,
                            data: null,
                            type: 'scatter',
                            itemStyle: {
                                normal: {
                                    color: '#FF0000',
                                    lineStyle: {
                                        color: '#FF0000'
                                    }
                                }
                            },
                            tooltip: {
                                trigger: 'item',
                                padding: 5,
                                backgroundColor: '#FF0000',
                                borderColor: '#FF0000',
                                borderWidth: 1,
                                formatter: function (obj) {
                                    var value = obj.value;
                                    return   "时间：" + value[0]+ '<br>'+obj.seriesName + "：" + value[1]
                                }
                            }
                        },
                        {
                            name: '卖出',
                            symbolSize: 10,
                            data: null,
                            type: 'scatter',
                            itemStyle: {
                                normal: {
                                    color: '#008000',
                                    lineStyle: {
                                        color: '#008000'
                                    }
                                }
                            },
                            tooltip: {
                                trigger: 'item',
                                padding: 5,
                                backgroundColor: '#008000',
                                borderColor: '#008000',
                                borderWidth: 1,
                                formatter: function (obj) {
                                    var value = obj.value;
                                    return  "时间：" + value[0]+ '<br>' +obj.seriesName + "：" + value[1]
                                }
                            },
                        }

                    ]
                };
                option.series[0].data = result.LastPrice;
                option.series[1].data = result.Buy_TradePrice;
                option.series[2].data = result.Sell_TradePrice;
                option.xAxis.data = result.Time;
                myChart.setOption(option);
            }
        $('#loading-center-absolute').css('display', 'none');
        }
    });
};
function InitBootstrapTable(my_url, my_table_id, my_columns, my_filename) {
          $('#'+my_table_id).bootstrapTable('destroy').bootstrapTable({
            url: my_url,
            method: 'get',
            columns: my_columns,
            paginationDetailHAlign:' hidden',
            toolbar: '#toolbar',       
            striped: true,          
            cache: false,           
            pagination: true,        
            sortable: true,      
            sortOrder: "asc",    
            queryParams: function (pageRequest) {
              return pageRequest;
            },
            sidePagination: "server",
            pageNumber: 1,           
            pageSize: 10,           
            pageList: [10, 25, 50, 100],
            search: true,        
            strictSearch: true,
            showColumns: true,      
            showRefresh: true,      
            minimumCountColumns: 2, 
            clickToSelect: true,    
            uniqueId: "_id",         
            showToggle: true,    
            cardView: false,      
            detailView: false,    
            //showExport: true,
            buttonsAlign: "right",
            exportDataType: "all",
            exportTypes: ['excel'],
            Icons: 'glyphicon-export',
            exportOptions: {
              fileName: my_filename,
            },
          })
        };


